﻿using System;
using System.IO;

namespace CoolpadContactConverter
{
    class SaveToDestnationState:IState
    {
        public Contact[] Contacts { get; set; }
 
        public IState Do()
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.Write("\r\n指定转换后的文件的位置。");
            Console.ForegroundColor = ConsoleColor.DarkGray;
            Console.WriteLine("例如E:\\linkman.txt。");

            TextWriter defaultOut = Console.Out;
            try
            {
                Console.ForegroundColor = ConsoleColor.White;
                using (TextWriter fileStream = new StreamWriter(Console.ReadLine().Trim(new char[]{' ','\"'})))
                {
                    Console.SetOut(fileStream);
                    Console.WriteLine("共读到" + Contacts.Length + "条联系人记录。");
                    foreach (Contact c in Contacts)
                        Console.WriteLine(c);
                }
            }
            catch (IOException e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.SetOut(defaultOut);
                Console.WriteLine(e.Message);

                return this;
            }
            catch (UnauthorizedAccessException e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.SetOut(defaultOut);
                Console.WriteLine(e.Message);

                return this;
            }

            Console.SetOut(defaultOut);
            return Program.SuccessState;
        }

   }
}
